package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.PurchaseDetailService;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    PurchaseDetailService purchaseDetailService;

    @Resource
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnReceive(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>().in("status", 0, 1)
        );
        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void mergePurchaseItem(PurchaseItemVo purchaseItemVo) {
        Long purchaseId;
        if (Objects.isNull(purchaseItemVo.getPurchaseId())) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATE.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        } else {
            purchaseId = purchaseItemVo.getPurchaseId();
        }
        // todo: 判断采购单状态处于未领取
        PurchaseEntity purchase = this.getById(purchaseId);
        if (purchase.getStatus() <= WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
            List<PurchaseDetailEntity> detailEntityList = purchaseItemVo.getItems().stream().map(item -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(item);
                purchaseDetailEntity.setPurchaseId(purchaseId);
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(detailEntityList);

            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setId(purchaseId);
            purchaseEntity.setUpdateTime(new Date());
            this.updateById(purchaseEntity);
        }

    }

    @Transactional
    @Override
    public void receivedPurchase(List<Long> ids) {
        // 1.确定当前采购单状态
        List<PurchaseEntity> purchaseEntityList = this.list(
                new QueryWrapper<PurchaseEntity>()
                        .in("id", ids)
                        .in("status", WareConstant.PurchaseStatusEnum.CREATE.getCode(), WareConstant.PurchaseStatusEnum.ASSIGNED.getCode())
        ).stream().peek(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVED.getCode());
            item.setUpdateTime(new Date());
        }).collect(Collectors.toList());

        // 2.更改采购单状态
        this.updateBatchById(purchaseEntityList);

        // 3.更新采购项目状态
        purchaseEntityList.forEach(item -> {
//            List<PurchaseDetailEntity> detailEntityList = purchaseDetailService.list(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", item.getId()))
//                    .stream().map(d -> {
//                        PurchaseDetailEntity detail = new PurchaseDetailEntity();
//                        detail.setId(d.getId());
//                        detail.setStatus(WareConstant.PurchaseDetailStatusEnum.PROGRESSING.getCode());
//                        return detail;
//                    }).collect(Collectors.toList());
//            purchaseDetailService.updateBatchById(detailEntityList);
            PurchaseDetailEntity detail = new PurchaseDetailEntity();
            detail.setStatus(WareConstant.PurchaseDetailStatusEnum.PROGRESSING.getCode());
            purchaseDetailService.update(detail, new UpdateWrapper<PurchaseDetailEntity>().eq("purchase_id", item.getId()));
        });
    }

    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        // 1. 改变采购单状态
        Long purchaseId = purchaseDoneVo.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);


        // 2. 改变采购项状态
        boolean success = true;
        List<PurchaseDetailEntity> purchaseDetailEntities = new ArrayList<>();
        for (PurchaseDoneVo.PurchaseItemDoneVo item : purchaseDoneVo.getItems()) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HAS_ERROR.getCode()) {
                success = false;
                purchaseDetailEntity.setStatus(item.getStatus());
            } else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.COMPLETED.getCode());
                // 3. 增加库存
                PurchaseDetailEntity detail = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(detail.getSkuId(), detail.getWareId(), detail.getSkuNum());

            }
            purchaseDetailEntity.setId(item.getItemId());
            purchaseDetailEntities.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(purchaseDetailEntities);

        purchaseEntity.setStatus(success ? WareConstant.PurchaseStatusEnum.COMPLETED.getCode() : WareConstant.PurchaseStatusEnum.HAS_ERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);

    }

}